﻿using RsaRegister.Model;
using RsaRegister;
using SoftRegManager.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;

namespace SoftRegManager.Forms
{
    public partial class FrmLicenseEdit : Form
    {
        private SoftInfo mSoftInfo;
        private GreatBLL mBLL;
        private RsaServer mRsaServer;

        public RegInfo RegInfo { get; private set; }
        public FrmLicenseEdit(SoftInfo softInfo, GreatBLL bLL,RegInfo regInfo=null)
        {
            InitializeComponent();
            mSoftInfo = softInfo;
            mBLL = bLL;
            RegInfo = regInfo;
            mRsaServer = new RsaServer(mSoftInfo.PriKey);
        }

        private void FrmLicenseEdit_Load(object sender, EventArgs e)
        {
            txtSoftName.Text = mSoftInfo.SoftName;
            LoadRegInfo(RegInfo);
            
        }

        private void LoadRegInfo(RegInfo regInfo=null)
        {
            if(regInfo != null)
            {
                if (mSoftInfo.SoftName != regInfo.SoftName)
                {
                    MessageBox.Show("软件名称不匹配!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                txtLicenseCode.Text = mRsaServer.GenerateRegisterCode(regInfo);
                btnExport.Enabled = true;
            }
            else
            {
                regInfo = new RegInfo();
            }
           
            txtUserName.Text = regInfo.User;
            dtExpired.Value = regInfo.ExpireDate;
            numTotalUsers.Value = regInfo.TotalUsers;
            txtCPUID.Text = regInfo.Cpuid;
            txtGUID.Text = regInfo.Guid.ToString();
            txtNote.Text = regInfo.Note;
            txtContact.Text = regInfo.Contact;
            txtTelephone.Text = regInfo.Telephone;
            txtEmail.Text = regInfo.Email;
                
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //RegInfo = BuildRegInfo();
            DialogResult = DialogResult.OK;
            Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            RefreshRegInfo();
            try
            {
                RegInfo = mBLL.SaveRegInfo(RegInfo);
                btnOK.Enabled = true;
                btnExport.Enabled = true;
                MessageBox.Show("注册信息已成功保存，请生成license文件发给用户", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"保存注册信息错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void btnGenLicense_Click(object sender, EventArgs e)
        {
            btnExport.Enabled = true;
            
            RefreshRegInfo();
            txtLicenseCode.Text = mRsaServer.GenerateRegisterCode(RegInfo);
            btnExport.Enabled = true;
        }
        private void RefreshRegInfo()
        {
            if (RegInfo == null) RegInfo = new RegInfo();
            RegInfo.SoftName = txtSoftName.Text;
            RegInfo.SoftId = mSoftInfo.SoftId;
            RegInfo.User = txtUserName.Text;
            RegInfo.Cpuid = txtCPUID.Text;
            RegInfo.Guid = new Guid(txtGUID.Text);
            RegInfo.ExpireDate = dtExpired.Value;
            RegInfo.TotalUsers = (int)numTotalUsers.Value;
            RegInfo.Note = txtNote.Text;
            RegInfo.Contact = txtContact.Text;
            RegInfo.Telephone = txtTelephone.Text;
            RegInfo.Email = txtEmail.Text;
            RegInfo.LastUpdated = DateTime.Now;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
           
            SaveFileDialog fd = new SaveFileDialog
            {
                RestoreDirectory=true,
                Title="选择或输入要输出的文件",
                Filter="授权文件(*.lic;*.dat)|*.lic;*.dat|所有文件(*.*)|*.*",
                InitialDirectory=Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments),
                FileName =RegInfo.SoftName+"_"+ RegInfo.User + ".lic"
            };
            if (fd.ShowDialog() == DialogResult.OK)
            {
               
                if (File.Exists(fd.FileName)) File.Delete(fd.FileName);
                mRsaServer.GenerateLicFile(fd.FileName, RegInfo);
                System.Diagnostics.Process.Start(Path.GetDirectoryName(fd.FileName));
            }
        }

        private void btnReadLicFile_Click(object sender, EventArgs e)
        {

            OpenFileDialog fd = new OpenFileDialog
            {
                RestoreDirectory = true,
                Title = "选择要导入的文件",
                Multiselect=false,
                Filter = "授权文件(*.lic;*.dat)|*.lic;*.dat|所有文件(*.*)|*.*",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };
            if(fd.ShowDialog()== DialogResult.OK)
            {
                RsaClient rsaClient = new RsaClient(mSoftInfo.PubKey);
                RegInfo = rsaClient.GetRegInfoFromLicFile(fd.FileName, out string regCode);

                if(RegInfo.SoftName!=mSoftInfo.SoftName)
                {
                    MessageBox.Show("授权文件错误：不是"+mSoftInfo.SoftName+"的授权文件","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                var status = rsaClient.AuthorizeCheck(fd.FileName);
                if(status== eAuthStatus.Fail)
                {
                    MessageBox.Show("授权失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if(status!= eAuthStatus.Guest&& RegInfo!=null)
                {
                    LoadRegInfo(RegInfo);
                }

            }
        }
    }
}
